package com.nsgf.library.ui.page;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.lifecycle.Observer;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.LimitLine.LimitLabelPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IFillFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.WaterDetailInfoBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityWaterDetailChartBinding;
import com.nsgf.library.databinding.ActivityWaterTrafficDetailChartBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.widget.MyMarkerView;
import com.nsgf.library.widget.prckerview.TimePickerView;
import com.nsgf.skjz.utils.Kits;
import com.nsgf.skjz.utils.ToastUtils;
import com.nsgf.skjz.utils.UnitTo;
import com.nsgf.skjz.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 水情
 */
public class WaterTrafficDetailActivity extends BaseActivity implements
        OnChartValueSelectedListener {

    WaterDetailStates mState;
    private AccountRequester mAccountRequester;
    protected Typeface tfRegular;
    private ActivityWaterTrafficDetailChartBinding mBinding;

    @Override
    protected void initViewModel() {

        mState = getActivityScopeViewModel(WaterDetailStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_water_traffic_detail_chart, BR.vm, mState)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);

        mState.titleBar.set(getIntent().getStringExtra("title"));
        mBinding = (ActivityWaterTrafficDetailChartBinding) getBinding();
        tfRegular = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");


        Calendar calendarStar = Calendar.getInstance();
        mState.startDate.set(ymd.format(calendarStar.getTime()));
        mState.startDateSrc.set(ymd.format(calendarStar.getTime()) + "\n08:00");
        starTime = calendarStar;


        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        mState.endDateSrc.set(ymd.format(calendar.getTime()) + "\n08:00");
        mState.endDate.set(ymd.format(calendar.getTime()));
        endTime = calendar;

        UnitTo.setBorder(this, R.color.radio_text_check_color, R.color.radio_text_check_color, R.color.white, mBinding.ivNsgfWorkPMonth, 5);
        UnitTo.setBorder(this, R.color.color_1D2129, R.color.white, R.color.color_1D2129, mBinding.ivNsgfWorkNMonth, 5);

        mBinding.chart1.setNoDataText("暂无相关数据");
        getDatas();
        mAccountRequester.getWaterDetailInfoResult().observe(this, new Observer<ResponseStatus<WaterDetailInfoBean>>() {
            @Override
            public void onChanged(ResponseStatus<WaterDetailInfoBean> responseStatus) {
                getController().dismissLoading();
                if (responseStatus.getResponseCode() == 200) {
                    mState.detailInfoBeanState.set(responseStatus.getData());
                    
                    // 检查数据是否为空
                    if (responseStatus.getData().getWaterRecordsList() == null || 
                        responseStatus.getData().getWaterRecordsList().isEmpty()) {
                        // 数据为空，恢复初始化状态，清空所有数据
                        clearAllData();
                    } else {
                        // 数据不为空，刷新数据
                        refreshData(responseStatus.getData());
                    }

                    initLineDataSet();
                    setData();

                } else {
                    // 请求失败，清空所有数据
                    clearAllData();
                    ToastUtils.showLongToast(responseStatus.getMsg());
                }
                getController().dismissLoading();
            }
        });
    }

    /**
     * 清空所有数据，恢复初始化状态
     */
    private void clearAllData() {
        // 清空数据更新时间
        mState.dataUpdateTime.set("");
        // 清空最后一条记录的流量值
        mState.lastRecordInq.set("");
        // 清空流量标题
        mState.trafficTitle.set("");
        
        // 重置图表数据
        if (mBinding.chart1 != null) {
            mBinding.chart1.clear();
            mBinding.chart1.invalidate();
        }
    }

    /**
     * 刷新数据
     */
    private void refreshData(WaterDetailInfoBean data) {
        // 设置数据更新时间 - 获取记录列表中的最后一条时间
        if (data.getWaterRecordsList() != null && !data.getWaterRecordsList().isEmpty()) {
            // 获取最后一条记录的时间
            WaterDetailInfoBean.WaterRecordsListBean lastRecord = 
                data.getWaterRecordsList().get(data.getWaterRecordsList().size() - 1);
            mState.dataUpdateTime.set("数据更新时间: " + lastRecord.getTm());
            // 设置最后一条记录的流量值
            mState.lastRecordInq.set(String.valueOf(lastRecord.getInq()));
        }

        // 设置汛限水位（如果API没有返回，使用默认值68.5）
        if (data.getRealTimeWaterLevel() != null) {
            if (data.getRealTimeWaterLevel().getFloodControlLevel() == 0) {
                data.getRealTimeWaterLevel().setFloodControlLevel(68.5);
            }
        }
    }

    /**
     * 数据加载
     */
    private void setData() {
        List<Entry> entries = new ArrayList<>();
        if (null == mState.detailInfoBeanState.get().getWaterRecordsList())
            return;

        for (int i = 0; i < mState.detailInfoBeanState.get().getWaterRecordsList().size(); i++) {
            WaterDetailInfoBean.WaterRecordsListBean data = mState.detailInfoBeanState.get().getWaterRecordsList().get(i);

            Entry entry = new Entry(i, (float) data.getInq());
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, "");
        lineDataSet.setColor(getResources().getColor(R.color.color_00EAFF));
        lineDataSet.setCircleColor(getResources().getColor(R.color.color_00EAFF));
        lineDataSet.setLineWidth(1f);
        lineDataSet.setCircleRadius(1f);
        lineDataSet.setDrawCircles(false);
        lineDataSet.setDrawValues(false);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        lineDataSet.enableDashedHighlightLine(10f, 5f, 0f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);
        lineDataSet.setFormLineWidth(0f);
        lineDataSet.setFormSize(15.f);
        //设置曲线展示为圆滑曲线（如果不设置则默认折线）
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        lineDataSet.setFillFormatter(new IFillFormatter() {
            @Override
            public float getFillLinePosition(ILineDataSet dataSet, LineDataProvider dataProvider) {
                return mBinding.chart1.getAxisLeft().getAxisMinimum();
            }
        });
        LineData lineData = new LineData(lineDataSet);
        mBinding.chart1.setData(lineData);


        float max = lineData.getYMax() + ((lineData.getYMax() - lineData.getYMin()) / 3);
        float min = lineData.getYMin() - ((lineData.getYMax() - lineData.getYMin()) / 3);

        mBinding.chart1.getAxisLeft().setAxisMaximum(max);
        mBinding.chart1.getAxisLeft().setAxisMinimum(min);
        mBinding.chart1.invalidate();
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     */
    private void initLineDataSet() {

        {   // // Chart Style // //

            // background color
            mBinding.chart1.setBackgroundColor(Color.WHITE);

            //是否展示网格线
            mBinding.chart1.setDrawGridBackground(false);
            //是否显示边界
            mBinding.chart1.setDrawBorders(false);
            // disable description text
            mBinding.chart1.getDescription().setEnabled(false);

            // enable touch gestures
            mBinding.chart1.setTouchEnabled(true);

            // set listeners
            mBinding.chart1.setOnChartValueSelectedListener(this);


            // enable scaling and dragging
            mBinding.chart1.setDragEnabled(true);
            mBinding.chart1.setScaleEnabled(true);
            // mBinding.chart1.setScaleXEnabled(true);
            // mBinding.chart1.setScaleYEnabled(true);

            // force pinch zoom along both axis
            mBinding.chart1.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = mBinding.chart1.getXAxis();

            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(1f);
            // vertical grid lines
            xAxis.enableGridDashedLine(10f, 10f, 0f);
            xAxis.setLabelRotationAngle(-30f);
            xAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (mState.detailInfoBeanState.get().getWaterRecordsList().size() == 0 || value < 0)
                        return "";
                    if ((int) value >= mState.detailInfoBeanState.get().getWaterRecordsList().size())
                        return "";
                    String tradeDate = mState.detailInfoBeanState.get().getWaterRecordsList().get((int) value).getTm();
                    return Utils.formatTime(tradeDate);
                }
            });
        }

        mBinding.chart1.setExtraBottomOffset(10f);//修复X轴设置RotationAngle后lable显示不全问题
        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = mBinding.chart1.getAxisLeft();
            // 绘制虚线网格
            yAxis.enableGridDashedLine(10f, 10f, 0f);

            // 设置Y轴数值格式，保留两位小数
            yAxis.setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    return String.format(Locale.getDefault(), "%.2f", value);
                }
            });
            // disable dual axis (only use LEFT axis)
            mBinding.chart1.getAxisRight().setEnabled(false);

        }

        // create marker to display box when values are selected

        MyMarkerView mv = new MyMarkerView(this, xAxis.getValueFormatter(), yAxis.getValueFormatter(), "水位", "#00EAFF", mState.detailInfoBeanState.get().getWaterRecordsList());
        mv.setChartView(mBinding.chart1);
        mBinding.chart1.setMarker(mv);
        mBinding.chart1.invalidate();

        {   // // Create Limit Lines // //
            LimitLine llXAxis = new LimitLine(9f, "Index 10");
            llXAxis.setLineWidth(1f);
            llXAxis.enableDashedLine(1f, 1f, 0f);
            llXAxis.setLabelPosition(LimitLabelPosition.RIGHT_BOTTOM);
            llXAxis.setTextSize(10f);
            llXAxis.setTypeface(tfRegular);
            // draw limit lines behind data instead of on top
            yAxis.setDrawLimitLinesBehindData(true);

            //xAxis.addLimitLine(llXAxis);
        }

        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);


        // draw points over time
        mBinding.chart1.animateX(1500);
        mBinding.chart1.animateY(1500);

        // get the legend (only possible after setting data)
        Legend l = mBinding.chart1.getLegend();
        //显示位置 左下方
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        // draw legend entries as lines
        l.setForm(LegendForm.LINE);
        l.setEnabled(false);
        while (!mBinding.chart1.isFullyZoomedOut()) {

            mBinding.chart1.zoomOut();
        }
    }

    private void getDatas() {
        mAccountRequester.diagramFlow(
                mState.startDate.get(),
                mState.endDate.get(),
                getIntent().getStringExtra("facilityCode"),
                getIntent().getStringExtra("label"),
                "water.obj.type.17");

    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        Log.i("LOW HIGH", "low: " + mBinding.chart1.getLowestVisibleX() + ", high: " + mBinding.chart1.getHighestVisibleX());
        Log.i("MIN MAX", "xMin: " + mBinding.chart1.getXChartMin() + ", xMax: " + mBinding.chart1.getXChartMax() + ", yMin: " + mBinding.chart1.getYChartMin() + ", yMax: " + mBinding.chart1.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }


    private Calendar starTime, endTime;

    private static SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static class WaterDetailStates extends StateHolder {

        public final State<WaterDetailInfoBean> detailInfoBeanState = new State<>(new WaterDetailInfoBean());
        public final State<String> dataUpdateTime = new State<>("");
        public final State<String> trafficTitle = new State<>("");
        public final State<String> lastRecordInq = new State<>("");

    }

    public class ClickProxy {

        public void pMonth() {

            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");


            endTime.setTime(starTime.getTime());
            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            getController().displayLoading();
            getDatas();

        }

        public void nMonth() {

            endTime.set(Calendar.DAY_OF_MONTH, endTime.get(Calendar.DAY_OF_MONTH) + 1);
            mState.endDate.set(Kits.Date.getYmd(endTime.getTimeInMillis()));
            mState.endDateSrc.set(Kits.Date.getYmd(endTime.getTimeInMillis()) + "\n08:00");

            starTime.setTime(endTime.getTime());
            starTime.set(Calendar.DAY_OF_MONTH, starTime.get(Calendar.DAY_OF_MONTH) - 1);
            mState.startDate.set(Kits.Date.getYmd(starTime.getTimeInMillis()));
            mState.startDateSrc.set(Kits.Date.getYmd(starTime.getTimeInMillis()) + "\n08:00");

            getController().displayLoading();
            getDatas();
        }


        public void screenStarTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(WaterTrafficDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.startDate.set(ymd.format(date));
                    mState.startDateSrc.set(ymd.format(date) + "\n08:00");

                    getDatas();
                    starTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("开始日期")
                    .setDate(starTime).build();

            mTimePickerView.show();


        }

        public void screenEndTime() {

            boolean[] type = new boolean[]{true, true, true, false, false, false};//显示类型 默认全部显示

            TimePickerView mTimePickerView = new TimePickerView.Builder(WaterTrafficDetailActivity.this, new TimePickerView.OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    mState.endDate.set(ymd.format(date));
                    mState.endDateSrc.set(ymd.format(date) + "\n08:00");
                    getDatas();
                    endTime.setTime(date);
                }
            }).isCyclic(false)
                    .setRangDate(null, null)
                    .setType(type)
                    .setTitleText("结束日期")
                    .setDate(endTime).build();

            mTimePickerView.show();


        }

    }
}
